package com.usian.controller;

import com.usian.feign.CartFeign;
import com.usian.feign.ItemFeign;
import com.usian.pojo.TbItem;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/frontend/cart")
public class CartWebController {

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private ItemFeign itemFeign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_COOKIE_EXPIRE}")
    private Long CART_COOKIE_EXPIRE;

    /**
     * 添加购物车（登陆以及未登陆）
     * @param userId
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/addItem")
    public Result addItem(@RequestParam String userId, @RequestParam Long itemId,
                          @RequestParam(defaultValue = "1") Integer num,
                          HttpServletRequest request,
                          HttpServletResponse response){
        try {
            /* 判断是否登陆 */
            if (StringUtils.isBlank(userId)){
                /* 未登录 */
                /* 获取cookie购物车中信息 */
                    Map<String, TbItem> map = getCartFromCookie(request);
                /* 更新购物车 */
                addItemToCart(map,itemId,num);
                /* 重新放入cookie中 */
                CookieUtils.setCookie(request,response,CART_COOKIE_KEY, JsonUtils.objectToJson(map),
                        CART_COOKIE_EXPIRE.intValue(),true);
                return Result.ok("OK");
            }else {
                /* 登陆状态 */
                /* 从redis中获取出信息 */
                Map<String,TbItem> cart = getCartFromRedis(userId);
                /* 商品添加到购物车 */
                addItemToCart(cart,itemId,num);
                /* 购物车缓存到redis中 */
                Boolean flag = addCartToRedis(userId,cart);
                if (flag){
                    return Result.ok();
                }
                return Result.error("error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("error");
        }
    }

    /**
     * 更新购物车到redis中
     * @param userId
     * @param cart
     * @return
     */
    private Boolean addCartToRedis(String userId,Map<String,TbItem> cart){
        return cartFeign.addCartToRedis(userId,cart);
    }

    /**
     * 从redis中获取
     * @param userId
     * @return
     */
    private Map<String,TbItem> getCartFromRedis(String userId){
        Map<String,TbItem> cart = cartFeign.getCartFromRedis(userId);
        if(cart!=null && cart.size()>0){
            return cart;
        }
        return new HashMap<String,TbItem>();
    }

    /**
     * 从cookie中获取购物车信息
     * @param request
     * @return
     */
    private Map<String, TbItem> getCartFromCookie(HttpServletRequest request){
        String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY, true);
        /* 判空 */
        if (StringUtils.isNotBlank(cookieValue)){
            Map<String, TbItem> map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return map;
        }
        return new HashMap<String, TbItem>();
    }

    /**
     * 更新购物车
     * @param map
     * @param itemId
     * @param num
     */
    private void addItemToCart(Map<String,TbItem> map,Long itemId,Integer num){
        /* 判断map中是否存在该商品 */
        TbItem tbItem = map.get(itemId.toString());
        if (tbItem!=null){
            /* 增加购物车中数量 */
            tbItem.setNum(tbItem.getNum()+num);
        }else {
            /* 购物车中不存在该商品信息 查询数据库 */
            tbItem = itemFeign.findItemById(itemId);
            tbItem.setNum(num);
        }
        /* 更新购物车 */
        map.put(itemId+"",tbItem);
    }

    /**
     * 展示购物车
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("showCart")
    public Result showCart(@RequestParam String userId,HttpServletRequest request,HttpServletResponse response){
        try {
            /* 判断是否登陆 */
            if (StringUtils.isBlank(userId)){
                /* 从cookie中获取 */
                String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY, true);
                Map<String,TbItem> map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
                List<TbItem> list = new ArrayList<>();
                for (TbItem value : map.values()) {
                    list.add(value);
                }
                return Result.ok(list);
            }else {
                /* 登陆 */
                /* redis中获取购物车 */
                Map<String, TbItem> cartFromRedis = getCartFromRedis(userId);
                List<TbItem> list = new ArrayList<>();
                for (TbItem value : cartFromRedis.values()) {
                    list.add(value);
                }
                return Result.ok(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("error");
        }
    }

    /**
     * 修改购物车
     * @param userId
     * @param num
     * @param itemId
     * @param response
     * @param request
     * @return
     */
    @RequestMapping("updateItemNum")
    public Result updateItemNum(@RequestParam String userId,@RequestParam Integer num,@RequestParam Long itemId,
                                HttpServletResponse response,HttpServletRequest request){
        try {
            if (StringUtils.isBlank(userId)){
                /* 未登录 */
                /* 获取cookie购物车中信息 */
                Map<String, TbItem> map = getCartFromCookie(request);
                /* 更新购物车 */
                TbItem tbItem = map.get(itemId+"");
                tbItem.setNum(num);
                map.put(itemId+"",tbItem);
                /* 重新放入cookie中 */
                CookieUtils.setCookie(request,response,CART_COOKIE_KEY, JsonUtils.objectToJson(map),
                        CART_COOKIE_EXPIRE.intValue(),true);
            }else {
                /* 登录 */
                /* redis中获取购物车信息 */
                Map<String, TbItem> cart = getCartFromRedis(userId);
                /* 修改购物车中的商品 */
                TbItem tbItem = cart.get(itemId.toString());
                tbItem.setNum(num);
                cart.put(itemId.toString(),tbItem);
                /* 更新redis中信息 */
                addCartToRedis(userId,cart);
            }
            return Result.ok("OK");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
    }

    /**
     * 删除购物车
     * @param itemId
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(@RequestParam Long itemId,@RequestParam String userId,
                                     HttpServletRequest request,HttpServletResponse response){
        try {
            if (StringUtils.isBlank(userId)){
                /* 未登录状态 */
                Map<String, TbItem> cart = getCartFromCookie(request);
                cart.remove(itemId+"");
                /* 重新放入cookie中 */
                CookieUtils.setCookie(request,response,CART_COOKIE_KEY, JsonUtils.objectToJson(cart),
                        CART_COOKIE_EXPIRE.intValue(),true);
            }else {
                /* 登陆 */
                /* 获得redis中的购物车 */
                Map<String, TbItem> cart = getCartFromRedis(userId);

                /* 删除购物车中的商品 */
                cart.remove(itemId.toString());

                /* 把购物车写到redis中 */
                addCartToRedis(userId,cart);
            }
            return Result.ok("OK!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }



}
